/**
 * 余额分配
 * @authors supmain (mtingfeng@gmail.com)
 * @date    2015-02-04 15:18:55
 * @for turn_bill.html
 */
var BSTYUN = BSTYUN || {};
BSTYUN.remainassign = {
	init: function(){
		var that = this;
		/* 初始化树 */
		that.initzTreeDrag();
	},
	initzTreeDrag: function(){
		var $exchange = $(".exchange") ,
			$clearall = $("#clearall") ,
			$psd = $("#paypsd") ,
			$brn_bar = $(".brn_bar") ,
			$remain = $("#remain") ;
		var beforeTreeId = null;
		var IDMark_A = "_a";
		var numReg = /^(\d*\.?\d+|\d+\.?\d*)$/i;	// 是否是数字: '.123' 、 '123.' 都合法   
		var setting = {
			view: {
				showIcon : false ,
				addDiyDom: addDiyDom
			},
			edit: {
				enable: true,
				showRemoveBtn: false,
				showRenameBtn: false,
				drag: {
					isCopy: false,
					isMove: true
				}
			},
			data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				beforeDrag: beforeDrag,
				beforeDrop: beforeDrop
			}
		};
		var zNodes =[
			{ id:1, pId:0, name:"父节点 1", open:true , group: true },
			{ id:11, pId:1, name:"叶子节点 1-1" , original: { id:11, pId:1, name:"叶子节点 1-1" } },
			{ id:12, pId:1, name:"父子节点 1-2" , group: true},
			{ id:121, pId:12, name:"叶子节点 1-2-1" , original: { id:121, pId:12, name:"叶子节点 1-2-1" }  },
			{ id:13, pId:1, name:"叶子节点 1-3" , original: { id:13, pId:1, name:"叶子节点 1-3" } },
			{ id:2, pId:0, name:"父节点 2", open:true , group: true },
			{ id:21, pId:2, name:"叶子节点 2-1" , original: { id:21, pId:2, name:"叶子节点 2-1" } },
			{ id:22, pId:2, name:"叶子节点 2-2" , original: { id:22, pId:2, name:"叶子节点 2-2" } },
			{ id:23, pId:2, name:"叶子节点 2-3" , original: { id:23, pId:2, name:"叶子节点 2-3" } },
			{ id:3, pId:0, name:"父节点 3", open:true , group: true },
			{ id:31, pId:3, name:"叶子节点 3-1" , original: { id:31, pId:3, name:"叶子节点 3-1" } },
			{ id:32, pId:3, name:"叶子节点 3-2" , original: { id:32, pId:3, name:"叶子节点 3-2" } },
			{ id:33, pId:3, name:"叶子节点 3-3" , original: { id:33, pId:3, name:"叶子节点 3-3" } }
		];
		// 添加input控件
		var tabindex = 0;
		function addDiyDom( treeId , treeNode ) {
			if( treeId == "all_users" ) return;
			if (treeNode.parentNode && treeNode.parentNode.id!=2) return;
			var aObj = $("#" + treeNode.tId + IDMark_A);
			if( treeNode ){
				var editStr = "<input type='text' placeholder='请输入金额' class='tree_input' id='amount_" + treeNode.id + "' tabindex='"+ ( ++tabindex ) +"' />";
				aObj.after(editStr);
				var btn = $("#diyBtn_"+treeNode.id);
				// 绑定事件
				if (btn) btn.on("blur", function(){
					var $this = $(this),
						value = $.trim( $this.val() );
					if( value != "" ){
						if( numReg.test( value ) ){
							$this.val( Number( value ) );
						}else{
							BSTYUN.dialog.warn("请输入正确的金额数字！",function(){
								$this.focus();
							});
						};
					};
				});
			};
		};
		// 开始拖拽之前
		function beforeDrag( treeId , treeNodes ) {
			beforeTreeId = treeId;
			for ( var i=0,l=treeNodes.length ; i<l; i++) {
				if ( treeNodes[i].drag === false || isJustGroup( treeNodes[i] ) ) {
					return false;
				};
			};
			return true;
		};
		// 结束拖拽之前
		function beforeDrop( treeId, treeNodes , targetNode, moveType ) {
			// 当前树的子节点不能变换位置。
			if( beforeTreeId == treeId ) {
				return false;
			};
			if( treeId == "assign_users" ){
				// 分配用户
				exchangeUserToAssign( treeNodes );
				return false;
			};
			if( treeId == "all_users" ){
				// 取消用户
				cancelUserToAssign( treeNodes );
				return false;
			};
			return targetNode ? targetNode.drop !== false : true;
		};
		// 判断是否是纯分组，纯分组不能拖拽
		function isJustGroup( node ){
			var flag = true ;
			if( node.group ){
				var children = node.children;
				if( children ){
					$.each( children , function( index , val ){
						flag = isJustGroup( val );
					} );
				}else{
					flag = true;
				};
			}else{
				flag = false ;
			};
			return flag;
		};
		// 获取子节点过滤父节点
		function getNodesFilterParents( node ){
			var array = [];
			if( node.isParent ){
				$.each( node.children , function( index , node ){
					array = array.concat( getNodesFilterParents( node ) );
				} );
			}else{
				array = array.concat( node );
			};
			return array ;
		};
		// 分配用户
		function exchangeUserToAssign( treeNodes ){
			$.each( treeNodes , function( index , node ){
				if( node.isParent ){
					// 父节点
					var childNodes = getNodesFilterParents( node ) ;
					updateTree( childNodes );
				}else{
					// 子节点
					updateTree( [node] );
				};
			} );
			function updateTree( nodes ){ // 参数为数组
				$.each( nodes , function( index , node ){
					if( node.group ) { return true; };
					usersTree.removeNode( node );
					assignTree.addNodes( null, node );
				} );
			};
		};
		// 取消分配用户
		function cancelUserToAssign( treeNodes ){
			$.each( treeNodes , function( index , node ){
				node.pId = node.original.pId;
				var parent = usersTree.getNodesByParam( "id" , node.pId , null)[0];
				assignTree.removeNode( node );
				usersTree.addNodes( parent , node );
			} );
		};
		var usersTree = $.fn.zTree.init($("#all_users"), setting, zNodes) ,
			assignTree = $.fn.zTree.init($("#assign_users"), setting) ;
		/* 分配用户 */
		$exchange.on("click",".toright",function(){
			var selectnodes = usersTree.getSelectedNodes();
			if( selectnodes.length > 0 ){
				exchangeUserToAssign( selectnodes );
			};
		}).on("click",".toleft",function(){
			var selectnodes = assignTree.getSelectedNodes();
			if( selectnodes.length > 0 ){
				cancelUserToAssign( selectnodes );
			};
		});
		/* 全部清除 */
		$clearall.on( "click" , function(){
			var selectnodes = assignTree.transformToArray(  assignTree.getNodes() );
			if( selectnodes.length > 0 ){
				cancelUserToAssign( selectnodes );
			};
		} );
		/* 确认分配 */
		$brn_bar.on("click",".confirm",function(){
			var psd = $.trim( $psd.val() );
			var data = getData();
			if( checkData( data ) ){
				if( psd != "" ){
					$.ajax({
						url: '',
						dataType: 'json',
						data: data ,
						beforeSend: null,
						complete: null,
						success: function( data ){
							
						},
						error: function(){
							BSTYUN.dialog.warn("网络异常请稍后再试！");
						}
					});
				}else{
					BSTYUN.dialog.warn("请输入密码！");
				};
			};
			
		} );
		function getData( ){
			var data = [],
				selectnodes = assignTree.transformToArray(  assignTree.getNodes() );
			$.each( selectnodes ,function( index , node ){
				var instance = new Object();
				instance.id = node.id;
				instance.account = $.trim( $("#amount_" + node.id ).val() );
				data.push( instance );
			} );
			return data;
		};
		function checkData( data ){
			var flag = true ,
				sum = 0 ,
				remain = Number( $.trim( $remain.text() ) );
			if( data.length == 0 ){
				BSTYUN.dialog.warn("请选择需要分配的人员！");
				return false;
			};
			$.each( data , function( index , val ){
				var account = val.account ,
					$account = $("#amount_" + val.id ) ;
				if( account == "" ){
					flag = false;
					BSTYUN.dialog.warn("金额数目不能为空！", (function( $account ){
						return function(){ $account.focus(); }
					})( $account ) );
					return false;
				};
				if( numReg.test( account ) ){
					var temple = Number( account ) ;
					sum += temple ;
					$account.val( temple );
				}else{
					flag = false;
					BSTYUN.dialog.warn("请输入正确的金额数字！",(function( $account ){
						return function(){ $account.focus(); }
					})( $account ) );
					return false;
				};
			} );
			if( flag ){
				if( sum > remain ){
					BSTYUN.dialog.warn("当前分配总额超出当前余额，请充值！");
					return false;
				};
			};
			return flag;
		};
	}
};
$(function(){
	BSTYUN.remainassign.init();
});